package org.example.managere.controller.feibiao;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.example.managere.dto.feibiao.AmArchivesBaseDto;
import org.example.managere.service.feibiao.AmArchivesBaseService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;

/**
 * 电机基本信息控制器
 */
@RestController
@RequestMapping("/api/feibiao/motor-base")
@RequiredArgsConstructor
public class AmArchivesBaseController {
    
    private final AmArchivesBaseService amArchivesBaseService;
    
    /**
     * 获取所有电机基本信息（分页）
     *
     * @param page 页码（从0开始）
     * @param size 每页大小
     * @param sort 排序字段
     * @return 电机基本信息分页结果
     */
    @GetMapping
    public ResponseEntity<Page<AmArchivesBaseDto>> getAllMotorBase(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String sort) {
        Pageable pageable;
        if (sort != null && !sort.isEmpty()) {
            String[] sortParams = sort.split(",");
            String sortField = sortParams[0];
            Sort.Direction direction = (sortParams.length > 1 && sortParams[1].equalsIgnoreCase("desc"))
                    ? Sort.Direction.DESC : Sort.Direction.ASC;
            pageable = PageRequest.of(page, size, Sort.by(direction, sortField));
        } else {
            pageable = PageRequest.of(page, size);
        }
        return ResponseEntity.ok(amArchivesBaseService.findAll(pageable));
    }
    
    /**
     * 根据ID获取电机基本信息
     *
     * @param motorId 电机ID
     * @return 电机基本信息
     */
    @GetMapping("/{motorId}")
    public ResponseEntity<AmArchivesBaseDto> getMotorBaseById(@PathVariable String motorId) {
        return amArchivesBaseService.findById(motorId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    /**
     * 创建电机基本信息
     *
     * @param amArchivesBaseDto 电机基本信息DTO
     * @return 创建后的电机基本信息
     */
    @PostMapping
    public ResponseEntity<AmArchivesBaseDto> createMotorBase(@RequestBody AmArchivesBaseDto amArchivesBaseDto) {
        return new ResponseEntity<>(amArchivesBaseService.save(amArchivesBaseDto), HttpStatus.CREATED);
    }
    
    /**
     * 更新电机基本信息
     *
     * @param motorId          电机ID
     * @param amArchivesBaseDto 电机基本信息DTO
     * @return 更新后的电机基本信息
     */
    @PutMapping("/{motorId}")
    public ResponseEntity<AmArchivesBaseDto> updateMotorBase(
            @PathVariable String motorId,
            @RequestBody AmArchivesBaseDto amArchivesBaseDto) {
        if (!motorId.equals(amArchivesBaseDto.getMotorId())) {
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok(amArchivesBaseService.update(amArchivesBaseDto));
    }
    
    /**
     * 删除电机基本信息
     *
     * @param motorId 电机ID
     * @return 无内容响应
     */
    @DeleteMapping("/{motorId}")
    public ResponseEntity<Void> deleteMotorBase(@PathVariable String motorId) {
        amArchivesBaseService.deleteById(motorId);
        return ResponseEntity.noContent().build();
    }
    
    /**
     * 搜索电机基本信息
     *
     * @param keyword 关键字
     * @param page 页码（从0开始）
     * @param size 每页大小
     * @return 符合条件的电机基本信息列表或分页结果
     */
    @GetMapping("/search")
    public ResponseEntity<?> searchMotorBase(
            @RequestParam String keyword,
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer size) {
        
        // 如果提供了分页参数，返回分页结果
        if (page != null && size != null) {
            Pageable pageable = PageRequest.of(page, size);
            return ResponseEntity.ok(amArchivesBaseService.searchByKeywordPaged(keyword, pageable));
        }
        
        // 否则返回完整列表
        return ResponseEntity.ok(amArchivesBaseService.searchByKeyword(keyword));
    }
    
    /**
     * 根据电机型号查询
     *
     * @param motorType 电机型号
     * @return 符合条件的电机基本信息列表
     */
    @GetMapping("/by-type")
    public ResponseEntity<List<AmArchivesBaseDto>> findByMotorType(@RequestParam String motorType) {
        return ResponseEntity.ok(amArchivesBaseService.findByMotorType(motorType));
    }
    
    /**
     * 根据制造商查询
     *
     * @param manufacturer 制造商
     * @return 符合条件的电机基本信息列表
     */
    @GetMapping("/by-manufacturer")
    public ResponseEntity<List<AmArchivesBaseDto>> findByManufacturer(@RequestParam String manufacturer) {
        return ResponseEntity.ok(amArchivesBaseService.findByManufacturer(manufacturer));
    }
} 